<template>
    <div>
        <!-- 编辑界面保存的信息 -->
        <div style="position: relative;">
            <component :is="dynamicComponent" v-model="formData"></component>
            <div class="toolbar">
                <InventorySales :params="InventorySalesParams"/>
                <QueryInventory :params="queryInventoryParams"/>
                <HistoricalDemandList :params="historicalDemandListParams"/>
            </div>
        </div>
        <!-- 审批信息 -->
        <div class="app-container">
            <el-row>
                <el-col :span="24">
                    <el-form :model="obj" class="my-form" ref="obj" :rules="rules" label-width="7rem"
                             label-position="right">
                        <el-row>
                            <el-col :span="24" class="my-plan-title-box">
                                <div class="my-info-title">需求审批信息</div>
                            </el-col>
                        </el-row>
                        <el-row class="basic-info-body">
                            <el-col :span="6">
                                <el-form-item label="审批数量" prop="approveNum">
                                    <el-input-number :disabled="disabled || !canApprovalEdit" v-model="obj.approveNum" :step="1"
                                                     step-strictly :min="1" placeholder=""/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="供货方式" prop="supplyMode">
                                    <el-select :disabled="disabled || !canApprovalEdit" v-model="obj.supplyMode" class="m-2"
                                               style="width: 100%" placeholder="">
                                        <el-option v-for="item in supply_mode_options" :key="item.value"
                                                   :label="item.label"
                                                   :value="item.value"/>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col  :span="6">
                                <el-form-item label="预估提货后全公司周转率" prop="coTurnoverRate">
                                    <el-input :disabled="disabled || !canApprovalEdit" v-model="obj.coTurnoverRate" placeholder=""/>
                                </el-form-item>
                            </el-col>
                            <el-col  :span="6">
                                <el-form-item label="预估提货后总仓周转率" prop="whseTurnoverRate">
                                    <el-input :disabled="disabled || !canApprovalEdit" v-model="obj.whseTurnoverRate" placeholder=""/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="审批意见" prop="comment">
                                    <el-input type="textarea" v-model="obj.comment" placeholder=""/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-col>
            </el-row>
            <div style="text-align:right;">
                <el-button @click="agree()">同意</el-button>
                <el-button @click="complete('N')">驳回</el-button>
                <el-button @click="doClose">取消</el-button>
            </div>
        </div>

    </div>
</template>

<script>
import filters from '@/components/approve/filters'
import {doGet, doPost, doPut, doDelete, doDownload} from '@/config/http'
import {supplyModeOptionsMap} from './supplyModeOptionsMap'
import {debounce} from '@/utils/debounce.js'
import InventorySales from '@/components/approve/InventorySales'
import QueryInventory from '@/components/approve/QueryInventory'
import HistoricalDemandList from '@/components/approve/HistoricalDemandList'
import {getPathByName} from "@/router";
import useUserStore from '@/store/modules/user'
import {isNullOrUndefined, notifyError} from "@/config/common";

export default {
    data() {
        const customValidator = (rule, value, callback) => {
            if (rule.min > 0 && !value) {
                console.log('aaaaa')
                callback(new Error(rule.label + '为必填项'))
                return
            }
            if (rule.max > 0 && value && value.length > rule.max) {
                callback(new Error(rule.label + '长度不能超过' + rule.max))
                return
            }
            callback()
        }
        const {supply_mode} = this.useDict('supply_mode')
        return {
            canApprovalEdit:false,
            disabled: false,
            formData: {},
            rules: {
                coTurnoverRate: [{
                    required: false,
                    validator: customValidator,
                    min: 0,
                    max: 100000,
                    label: '预估提货后全公司周转率',
                    trigger: ['blur', 'change']
                }],
                whseTurnoverRate: [{
                    required: false,
                    validator: customValidator,
                    min: 0,
                    max: 100000,
                    label: '预估提货后总仓周转率',
                    trigger: ['blur', 'change']
                }],
            },
            obj: {
                approveNum: '',
                supplyMode: '',
                coTurnoverRate: '',
                whseTurnoverRate: '',
                comment: '', // 审批意见
            },
            supply_mode,
            isPM: useUserStore().isPM, // 是否产品经理
        }
    },
    watch: {
        TurnoverRate: {
            immediate: true,
            handler: function (val) {
                if (val) {
                    this.rules.coTurnoverRate[0].required = true
                    this.rules.coTurnoverRate[0].min = 1
                    this.rules.whseTurnoverRate[0].required = true
                    this.rules.whseTurnoverRate[0].min = 1
                } else {
                    this.rules.coTurnoverRate[0].required = false
                    this.rules.coTurnoverRate[0].min = 0
                    this.rules.whseTurnoverRate[0].required = false
                    this.rules.whseTurnoverRate[0].min = 0
                }
                this.$nextTick(() => {
                    setTimeout(() => {
                        this.$refs.obj.clearValidate()
                    }, 100)
                })
            }
        },
        formData: {
            handler: debounce(function (newVal) {
                console.log('xxx', newVal,)
                this.obj.approveNum = newVal.approveNum ? newVal.approveNum : newVal.submitQuantity
                this.obj.supplyMode = newVal.supplyMode
                this.obj.coTurnoverRate = newVal.coTurnoverRate
                this.obj.whseTurnoverRate = newVal.whseTurnoverRate
                this.obj.comment = newVal.comment
                if (newVal.rogFlag === '1') {
                    this.disabled = true
                }
            }),
            deep: true,
        }

    },
    computed: {
        TurnoverRate() {
            let res = false
            let prepaidFlag = this.formData.prepaidFlag // 是否预付物料
            let rogFlag = this.formData.rogFlag // 退货标识
            if (prepaidFlag === '1' && rogFlag !== '1') {
                res = true
            }
            return res
        },
        turnoverRateShow() {
            let billTypeCode = this.$route.query.billTypeCode
            let str = "PLAN-NB,PLAN-Z1,PLAN-Z4"
            return str.includes(billTypeCode)
        },
        supply_mode_options() {
            let billTypeCode = this.$route.query.billTypeCode
            let supplyModeOptionsMapRes = null
            if (this.formData.rogFlag === '1') {
                supplyModeOptionsMapRes = supplyModeOptionsMap.get('TUIHUO')
            } else {
                supplyModeOptionsMapRes = supplyModeOptionsMap.get(billTypeCode)
            }
            if (!this.obj.supplyMode) this.obj.supplyMode = supplyModeOptionsMapRes.default
            let options = []
            for (let i = 0; i < this.supply_mode.length; i++) {
                let item = this.supply_mode[i]
                if (supplyModeOptionsMapRes.options.indexOf(item.value) !== -1) {
                    options.push(item)
                }
            }
            return options
        },
        dynamicComponent() {
            let component = filters(this.$route.query.billTypeCode).component
            return component
        },
        historicalDemandListParams() {
            const {formData} = this
            return {
                appUnitCode: formData.appUnitCode, // 申请单位
                materialCode: formData.materialCode, // 物料编码
                purFactory: formData.purFactory, // 采购工厂
                purGroupCode: formData.purGroupCode, // 采购组编码
                purInventoryAdd: formData.purInventoryAdd, // 采购库存地点
                reportFactoryCode: formData.reportFactoryCode // 提报工厂
            }
        },
        InventorySalesParams() {
            const {formData} = this
            return {
                materialCode: formData.materialCode, // 物料编码
                factory: formData.reportFactoryCode, // 提报工厂
                inventoryAdd: formData.purInventoryAdd, // 采购库存地点
                approveNum: formData.submitQuantity //提报数量
            }
        },
        queryInventoryParams() {
            const {formData} = this
            return [{
                materialCode: formData.materialCode, // 物料编码
                purFactory: formData.reportFactoryCode, // 提报工厂
                purInventoryAdd: formData.purInventoryAdd, // 采购库存地点
                availableStockRuleCode: 'A'
            }]
        }
    },
    components: {InventorySales, QueryInventory, HistoricalDemandList},
    created() {
        this.setApprovalEdit()
    },
    methods: {
        setApprovalEdit() {
            let { taskName } = this.$route.query
            if (taskName?.includes('产品经理')) {
                this.canApprovalEdit = true
            }else{
                this.canApprovalEdit = false
            }
        },
        verifyData(params) {
            if (params.approveFlag === 'N' && !params.comment) {
              notifyError('请输入审批意见')
              return false
            } else {
              return true
            }
        },
        // 同意
        agree() {
            const {obj: {approveNum}, formData: {planDod}} = this
            if (!planDod) {
                this.$message.error('请选择计划交货日期')
                return false
            }
            if (approveNum < 1) {
                this.$message.error('审批数量不能小于等于0')
                return false
            }
            this.$refs['obj'].validate(valid => {
                if (!valid) {
                    return
                }
                this.complete('Y')
            })
        },
        /**
         * 同意 驳回
         * @param {*} val Y 同意  N 驳回
         */
        complete(val) {
            let newObj = Object.assign({}, this.obj)
            delete newObj.comment
            let formData = {}
            Object.keys(this.formData).forEach(key => {
                if (isNullOrUndefined(this.formData[key])) {
                    formData[key] = ''
                } else {
                    formData[key] = this.formData[key]
                }
            })
            let attachments = ''
            if (Array.isArray(formData.attachments)) {
                attachments = JSON.stringify(formData.attachments)
            } else {
                attachments = formData.attachments
            }
            let reqItemExVoObj = {
                ...formData,
                ...newObj,
                taskName:this.$route.query.taskName
            }
            let params = {
                comment: this.obj.comment,	// 审批意见
                approveFlag: val, // 同意 驳回
                approvalItemVoList: [{
                    procInsId: this.$route.query.procInsId,	// 流程实例ID
                    taskId: this.$route.query.taskId,	// 任务唯一标识
                    reqItemExVo: {
                        ...reqItemExVoObj,
                        attachments: attachments,
                        approveAmount : reqItemExVoObj.reportPrice * reqItemExVoObj.approveNum
                    }
                }],
            }
            if (!this.verifyData(params)) return false

            if(params.comment){
                params.comment = (val == 'Y' ? '同意：' : '驳回：') + params.comment
            }else{
                params.comment = '同意'
            }
            doPost('peas-module-plan-biz', '/req/approval-modify', params).then(res => {
                this.doClose()
            })
        },
        doClose() {
            let path = getPathByName('BpmTodo')
            // const obj = {path: '/bpm/task-management/todo'}
            const obj = {path}
            this.$tab.closeOpenPage(obj)
        },
    }
}
</script>

<style scoped lang="scss">
.app-container {
  .my-info-title-box {
    margin-bottom: 1rem;

    .color-block {
      float: left;
      width: 0.38rem;
      height: 1.3rem;
      background-color: rgb(48, 135, 180);
      margin-right: 0.5rem;
    }

    .my-info-title {
      display: contents;
      font-weight: 650;
      font-style: normal;
      font-size: 1rem;
      line-height: 1.3rem;
      color: #1600FF;
    }
  }

  .basic-info-body {
    margin-bottom: 2rem;
  }
}

.toolbar {
  position: absolute;
  right: 0;
  padding: 5px;
  top: 10px;
  display: flex;
  justify-content: flex-end;

  & > * {
    margin-right: 10px;
  }
}
</style>
